#include "StdAfx.h"
#include "Client.hpp"
#include "Server.hpp"

HpsFramework::Network::Server* HpsFramework::Network::Client::getServer()
{
	return this->_server;
}

void HpsFramework::Network::Client::close( bool shutdn /*= true */ )
{
	this->disconnect ( shutdn );
}

void HpsFramework::Network::Client::disconnect( bool graceful /*= true */ )
{

	if(graceful)
	{
		this->setRemoval();
	}
	else
	{
		this->setDisconnection();
	}

}

void HpsFramework::Network::Client::write( byteptr buf, size bufSize )
{

	if(this->isDisconnectionSet()) 
	{
		// you cannot send any data if client has been marked for removal
		return;
	}

	if(!this->getWriter()->getBuffer()->enqueue ( buf, bufSize ))
	{
		this->getServer()->onServerError("Error enqueueing packet to write buffer: buffer is too small", -1);
		return;
	}

}

HpsFramework::Network::NetReader* HpsFramework::Network::Client::getReader()
{
	return &this->_reader;
}

HpsFramework::Network::NetWriter* HpsFramework::Network::Client::getWriter()
{
	return &this->_writer;
}

HpsFramework::Network::Client::Client( HpsFramework::Network::Socket& other, HpsFramework::Network::Server* srv, HpsFramework::Network::Client::IdType id ) 
	: Socket(other), _remove(false), _disconnect(false), _server(srv), _uid(id)
{
}

HpsFramework::Network::Client::~Client( void )
{
}

bool HpsFramework::Network::Client::isDisconnectionSet()
{
	return this->_disconnect;
}

HpsFramework::Network::Client::IdType HpsFramework::Network::Client::getId()
{
	return this->_uid;
}

bool HpsFramework::Network::Client::isRemoveSet()
{
	return this->_remove;
}

void HpsFramework::Network::Client::setDisconnection()
{
	this->_disconnect = true;
}

void HpsFramework::Network::Client::setRemoval()
{
	this->_remove = true;
}

void HpsFramework::Network::Client::writeBuffer( Protocol::ProtocolBuffer* buffer )
{
	if(buffer->getBuffer())
	{
		this->write(buffer->getBuffer(), buffer->getSize());
	}
}
